package utils

import (
	"math/rand"
	"time"
	"fmt"
	"os"
	"runtime/debug"
)

func CheckFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}

	return exist
}

func SafeCall(callback func(args ...interface{}) error, iargs ...interface{}) error {
	defer func() {
		if err := recover(); err != nil {
			rval := rand.Intn(100)
			now := time.Now()
			filename := fmt.Sprintf("[%d-%02d-%02d-%02d-%02d-%02d]_%d.dump", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(),
				now.Second(), rval)

			var f *os.File
			//var err error
			if CheckFileIsExist(filename) {
				f, _ = os.OpenFile(filename, os.O_APPEND, 0666)
			} else {
				f, _ = os.Create(filename)
			}

			defer f.Close()
			f.Write([]byte(err.(error).Error()))
			f.Write(debug.Stack())
		}
	}()

	return callback(iargs...)
}
